<?php


namespace App\Services;
use App\Exceptions\ApiException;
use App\Models\ConstellationsCache;
use GuzzleHttp\Client;

class ConstellationServices
{
    protected $client;

    protected $key = '';

    const BASE_URL = 'http://web.juhe.cn:8080/constellation/getAll?consName=%s&type=%s&key=%s';

    const COSTELLS = ['白羊座', '金牛座', '双子座', '巨蟹座',
        '狮子座', '处女座', '天秤座', '天蝎座',
        '射手座', '摩羯座', '水瓶座', '双鱼座',];

    const ALLOW_TYPES = ['today', 'tomorrow', 'week', 'month', 'year'];

    public function __construct(Client $client)
    {
        $this->client = $client;
        $this->key = config('constellation.constellation_key');
    }

    public function getConstellValue($constellation, $type)
    {
        if (! in_array($constellation, self::COSTELLS) || ! in_array($type, self::ALLOW_TYPES)) {
            throw new ApiException('参数异常', 1);
        }
        $date = date('Y-m-d', time());
        $cache = $this->getConstellValueFormCache($constellation, $type, $date);
        if (! $cache === false) {
            return $cache;
        }
        $result = $this->getConstellValueFormApi($constellation, $type);
        $this->saveApiDataToCache($constellation, $type, $result);
        return $result;
    }

    protected function getConstellValueFormCache($constellation, $type, $date)
    {
        $cache = ConstellationsCache::query()->where('constellation_name', $constellation)
            ->where('type', $type)
            ->where('date', $date)
            ->first();

        if (empty($cache)) {
            return false;
        }
        return json_decode($cache->cache_info, true);
    }

    protected function getConstellValueFormApi($constellation, $type)
    {
        $url = sprintf(self::BASE_URL, $constellation, $type, $this->key);
        $response = $this->client->get($url);
        $resultStr = (string) $response->getBody();
        $result = json_decode($resultStr, true);
        if (isset($result['error_code']) && $result['error_code'] === 0) {
            return $result;
        }
        throw new ApiException('网络错误', 1);
    }

    protected function saveApiDataToCache(string $constellation, string $type, array $cache_info)
    {
        ConstellationsCache::query()->create([
            'constellation_name' => $constellation,
            'type' => $type,
            'cache_info' => json_encode($cache_info),
            'date' => date('Y-m-d', time()),
        ]);
    }
}
